<template>
  <el-dialog title="优惠券发放任务" :visible.sync="dialogVisible" width="800px">
    <el-form :model="sendForm" label-position="right" label-width="100px" ref="sendForm" v-if="pageType === 'form'"
      :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="sendForm.taskName" placeholder="任务名称" :disabled="editId !== undefined" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="发放批次" prop="batchIdList">
        <el-select v-model="sendForm.batchIdList" :multiple="sendType === 'AUTO'" placeholder="发放批次" :disabled="editId !== undefined">
          <el-option v-for="item in batchIdList" :key="item.batchId" :label="`${item.batchId}-${item.couponName}`"
            :value="item.batchId" />
        </el-select>
      </el-form-item>
      <el-form-item label="发放数量" prop="grantQuantity">
        <el-input-number v-model="sendForm.grantQuantity" :min="1" controls-position="right" :disabled="editId !== undefined" />
      </el-form-item>
      <el-form-item label="领取时间" prop="date">
        <el-date-picker v-model="sendForm.date" type="datetimerange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" :picker-options="{ disabledDate }" />
      </el-form-item>
      <el-form-item label="任务时间" prop="dates" v-if="sendType === 'AUTO'">
        <el-date-picker v-model="sendForm.dates" type="datetimerange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" :picker-options="{ disabledDate }" />
      </el-form-item>
      <el-form-item label="发放人群" prop="targetType">
        <el-select v-model="sendForm.targetType" placeholder="发放人群" :disabled="editId !== undefined">
          <el-option label="标签人群" value="TAG" />
          <el-option label="自定义人群" value="CUSTOM" />
          <el-option label="特定人群" value="SPECIFIC" v-if="sendType === 'AUTO'" />
        </el-select>
      </el-form-item>
      <el-form-item label="标签人群" prop="tagIdList" v-if="sendForm.targetType === 'TAG'">
        <el-select v-model="sendForm.tagIdList" multiple placeholder="标签人群" :disabled="editId !== undefined">
          <el-option v-for="item in usersTagList" :key="item.id" :label="item.tagName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="自定义人群" prop="uidIdList" v-if="sendForm.targetType === 'CUSTOM'" style="margin-bottom: 0;">
        <el-input type="textarea" :rows="4" v-model="sendForm.uidIdList" placeholder="自定义人群(多个uid，换行隔开)" :disabled="editId !== undefined" />
      </el-form-item>
      <el-form-item label=" " v-if="sendForm.targetType === 'CUSTOM' && editId!==undefined">
        <div class="upload-container" @click="handleUpdateFile">
          <i class="el-icon-upload2" /> 选择文件
          <input type="file" id="file-upload"
            accept=".xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            style="display: none;" @change="changeFile">
        </div>
      </el-form-item>
      <el-form-item label="特定人群" prop="specificType" v-if="sendForm.targetType === 'SPECIFIC'">
        <el-select v-model="sendForm.specificType" placeholder="特定人群" :disabled="editId !== undefined">
          <el-option v-for="item in userTypeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <template v-if="sendType === 'AUTO'">
        <el-form-item label="发放节点" prop="grantNode">
          <el-select v-model="sendForm.grantNode" placeholder="发放节点" :disabled="editId !== undefined">
            <el-option v-for="item in sendNodeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="持有上限" prop="maxHoldQuantity">
          <el-input-number v-model="sendForm.maxHoldQuantity" :min="1" controls-position="right" :disabled="editId !== undefined" />
        </el-form-item>
      </template>

    </el-form>
    <el-descriptions title="优惠券发放详情" :column="1" border v-if="pageType === 'view'" width="800px">
      <el-descriptions-item label="任务名称">{{ detail.taskName }}</el-descriptions-item>
      <el-descriptions-item label="发放批次">{{ parseBatchIdList(detail.batchIdList) }}</el-descriptions-item>
      <el-descriptions-item label="发放数量">{{ detail.grantQuantity }}</el-descriptions-item>
      <el-descriptions-item label="领取时间">{{ `${detail.claimStart}至${detail.claimEnd}` }}</el-descriptions-item>
      <el-descriptions-item label="任务时间" v-if="sendType === 'AUTO'">
        {{ `${detail.validFrom}至${detail.validTo}` }}
      </el-descriptions-item>
      <el-descriptions-item label="发放人群">{{ targetType[detail.targetType] }}</el-descriptions-item>
      <el-descriptions-item label="标签人群" v-if="detail.targetType === 'TAG'">
        {{ parseTagIdList(detail.tagIdList) }}
      </el-descriptions-item>
      <el-descriptions-item label="自定义人群" v-if="detail.targetType === 'CUSTOM'">
        {{ detail.uidIdList.join('，') }}
      </el-descriptions-item>
      <el-descriptions-item label="特定人群" v-if="detail.targetType === 'SPECIFIC'">
        {{ userTypeList[detail.specificType] }}
      </el-descriptions-item>
      <el-descriptions-item label="发放节点" v-if="sendType === 'AUTO'">{{ detail.grantNode }}</el-descriptions-item>
      <el-descriptions-item label="持有上限" v-if="sendType === 'AUTO'">{{ detail.maxHoldQuantity }}</el-descriptions-item>
    </el-descriptions>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" v-if="pageType === 'form'" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { sendType, targetType, userTypeList, sendNode } from '@/constants/coupon';
import { openingCouponList, queryUserTagList, addSendTask, editSendTask } from '@/api/coupon';
import moment from 'moment';
import { userTagList } from '@/constants/activity';
// import XLSX from 'xlsx';
export default {
  props: ['sendType', 'getTableData'],
  created() {
    this.createSelectData(targetType, 'targetTypeList');
    this.createSelectData(sendNode, 'sendNodeList');
  },
  mounted() {
    this.queryOpeningCouponList();
    this.queryUserTag();
  },
  data() {
    return {
      pageType: 'form',
      dialogVisible: false,
      userTypeList,
      targetType,
      userTagList,
      editId: undefined,
      sendForm: {
        taskType: this.sendType,
        taskName: undefined,
        batchIdList: [],
        grantQuantity: 1,
        date: [],
        dates: [],
        targetType: undefined,
        tagIdList: [],
        uidIdList: undefined,
        specificType: undefined,
        grantNode: undefined,
        maxHoldQuantity: 1
      },
      rules: {
        taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        batchIdList: [{ required: true, message: '请选择发放批次', trigger: 'blur' }],
        grantQuantity: [{ required: true, message: '请输入发放数量', trigger: 'blur' }],
        date: [{ required: true, message: '请设置领取时间', trigger: 'blur' }],
        dates: [{ required: true, message: '请设置任务时间', trigger: 'blur' }],
        targetType: [{ required: true, message: '请选择目标人群', trigger: 'blur' }],
        tagIdList: [{ required: true, message: '请选择用户标签', trigger: 'blur' }],
        uidIdList: [{ required: true, message: '请设置目标人群', trigger: 'blur' }],
        specificType: [{ required: true, message: '请选择特定人群', trigger: 'blur' }],
        grantNode: [{ required: true, message: '请选择发放节点', trigger: 'blur' }],
        maxHoldQuantity: [{ required: true, message: '请输入持有上限', trigger: 'blur' }],
      },
      targetTypeList: [],
      sendNodeList: [],
      batchIdList: [],
      usersTagList: [],
      detail: {}
    }
  },
  methods: {
    // 解析券批次
    parseBatchIdList(ids = []) {
      return ids.map(id => {
        const batch = this.batchIdList.find(item => item.value === id)
        return batch ? batch.couponName : id
      }).join(',')
    },
    // 解析标签人群
    parseTagIdList(ids = []) {
      return ids.map(id => {
        const tag = this.userTagList.find(item => item.id === id)
        return tag ? tag.tagName : id
      }).join(',')
    },
    handleUpdateFile() {
      document.getElementById('file-upload').click()
    },
    showModal(type) {
      this.pageType = type
      this.dialogVisible = true
    },
    closeDialog() {
      if (this.pageType === 'form') {
        this.$refs.sendForm.resetFields();
      }
      this.dialogVisible = false;
      this.editId = undefined;
    },
    disabledDate(date) {
      return moment().isAfter(date, 'second')
    },
    changeFormValue(value) {
      this.showModal('form');
      this.sendForm = value;
      this.editId = value.id
    },
    changeDetail(detail) {
      this.detail = detail;
      this.showModal('view');
    },
    createSelectData(source, current) {
      // 这个方法是将枚举数据转换成list数据
      const typeList = [];
      Object.keys(source).map(item => {
        const typeItem = {
          value: item,
          label: source[item]
        };
        typeList.push(typeItem)
      })
      this[current] = typeList;
    },
    async queryOpeningCouponList() {
      const { code, data } = await openingCouponList()
      if (code !== 200) return;
      this.batchIdList = data || []
    },
    queryUserTag() {
      queryUserTagList().then(res => {
        if (res.code === 200) {
          this.usersTagList = res.data
        }
      })
    },
    changeFile(event) {
      const XLSX = require('xlsx');
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const sheetName = workbook.SheetNames[0]; // 获取第一个工作表的名称
        const sheet = workbook.Sheets[sheetName]; // 获取工作表数据
        const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 });
        this.sendForm.uidIdList = jsonData.flat().join('\n')
      };
      reader.readAsArrayBuffer(file)
    },
    handleSubmit() {
      this.$confirm('是否确认创建')
        .then(res => {
          this.$refs.sendForm.validate(async (valid) => {
            if (!valid) return;
            const params = { ...this.sendForm };
            if (params.targetType === 'CUSTOM') {
              params.uidIdList = params.uidIdList.split('\n');
            } else {
              delete params.uidIdList;
            }
            if (this.sendType === 'MANUAL') {
              params.batchIdList = [params.batchIdList]
            }
            params.taskType = this.sendType;
            if (this.sendType === 'AUTO') {
              params.validFrom = moment(params.dates[0]).format('YYYY-MM-DD HH:mm:ss');
              params.validTo = moment(params.dates[1]).format('YYYY-MM-DD HH:mm:ss');
            }
            params.claimStart = moment(params.date[0]).format('YYYY-MM-DD HH:mm:ss');
            params.claimEnd = moment(params.date[1]).format('YYYY-MM-DD HH:mm:ss');

            if (this.editId) return this.updateRow(params)
            return this.createRow(params)
          })
        })
        .catch(_ => { });


    },
    async updateRow(params) {
      const { code } = editSendTask({ id: this.editId, ...params })
      if (code !== 200) return;
      this.$message({ message: '修改成功', type: 'success' });
      this.closeDialog();
      this.getTableData();
    },
    async createRow(params) {
      const { code } = await addSendTask(params)
      if (code !== 200) return;
      this.$message({ message: '添加成功', type: 'success' });
      this.closeDialog();
      this.getTableData();
    },
  }
}
</script>

<style scoped lang="scss">
.toolTipNumber {
  height: auto;

  .toolTipNumberFooter {
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.upload-container {
  width: 178px;
  margin-top: 10px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  text-align: center;
  overflow: hidden;

  &:hover {
    color: #409EFF;
    border-color: #409EFF;
  }
}

.custom-upload-button {
  display: inline-block;

  background-color: transparent;
  color: #46a6ff;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.custom-upload-button:hover {
  background-color: transparent;
}

.icon {
  margin-right: 10px;
}

#file-name {
  margin-top: 10px;
  font-size: 14px;
  color: #333;
}
</style>
